from django.shortcuts import render
import json
import re
from django.views.generic.base import View
from django.http import HttpResponse
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404
from django.core.serializers.json import DjangoJSONEncoder
from utils.mixin_utils import LoginRequiredMixin
from rbac.models import Menu
from system.models import SystemSetup
from .models import *
from .forms import *

User = get_user_model()


# Create your views here.

class EquipmentView(LoginRequiredMixin, View):
    """
    工单视图：根据前端请求的URL 分为个视图：我创建的工单、我审批的工单和我收到的工单
    """

    def get(self, request):
        ret = Menu.getMenuByRequestUrl(url=request.path_info)
        ret.update(SystemSetup.getSystemSetupLastData())
        print(ret)
        return render(request, 'equipment/eas_index.html', ret)


class EIMView(LoginRequiredMixin, View):
    """
    工单视图：根据前端请求的URL 分为个视图：我创建的工单、我审批的工单和我收到的工单
    """

    def get(self, request):
        ret = Menu.getMenuByRequestUrl(url=request.path_info)
        return render(request, 'equipment/eim/bim.html', ret)


class BIMListView(LoginRequiredMixin, View):
    """
    工单列表：通过前端传递回来的url来区分不同视图，返回相应列表数据
    """
    def get(self, request):
        fields = ['equipment_number', 'equipment_name', 'equipment_type', 'equipment_status', 'production_date']
        filters = dict()
        if 'number' in request.GET and request.GET['number']:
            filters['equipment_number'] = request.GET['number']
        if 'equipment_type' in request.GET and request.GET['equipment_type']:
            filters['equipment_type'] = request.GET['equipment_type']
        ret = dict(data=list(Equipment_info.objects.filter(**filters).values(*fields).order_by('equipment_number')))

        return HttpResponse(json.dumps(ret, cls=DjangoJSONEncoder), content_type='application/json')


class BIMCreateView(LoginRequiredMixin, View):

    def auto_number(self):
        last_number = Equipment_info.objects.last()
        last_number=str(last_number)
        number = "".join(list(filter(str.isdigit, last_number)))
        number = int(number)+1
        return 'E'+str(number)

    def get(self, request):
        ret = dict()
        if 'equipment_number' in request.GET and request.GET['equipment_number']:
            print(request.GET['equipment_number'])
            equipment = get_object_or_404(Equipment_info, pk=request.GET.get('equipment_number'))
            equipment_update_form = BIMCreate(request.GET, instance=equipment)
            ret['form'] = equipment_update_form
        else:
            equipment_number = self.auto_number()
            equipment = Equipment_info()
            print(equipment_number)
            equipment_create_form = BIMCreate(request.GET, initial={'equipment_number':equipment_number},instance=equipment)
            ret['form'] = equipment_create_form
        return render(request, 'equipment/eim/bim_create_new.html', ret)

    def post(self, request):
        res = dict()
        bim_create_form = BIMCreate(request.POST)

        if 'equipment_number' in request.POST and request.POST['equipment_number']:
            equipment = get_object_or_404(Equipment_info, pk=request.POST.get('equipment_number'))
            equipment_update_form = BIMCreate(request.POST, instance=equipment)
            if equipment_update_form.is_valid():
                equipment_update_form.save()
                res['status'] = 'success'
            else:
                pattern = '<li>.*?<ul class=.*?><li>(.*?)</li>'
                errors = str(equipment_update_form.errors)
                bim_update_form_errors = re.findall(pattern, errors)
                res = {
                    'status': 'fail',
                    'bim_update_form_errors': bim_update_form_errors[0]
                }
        else:
            equipment = Equipment_info()
            equipment_create_form = BIMCreate(request.POST,instance=equipment)
            if equipment_create_form.is_valid():
                equipment_create_form.save()
                res['status'] = 'success'
            else:
                pattern = '<li>.*?<ul class=.*?><li>(.*?)</li>'
                errors = str(equipment_create_form.errors)
                bim_create_form_errors = re.findall(pattern, errors)
                res = {
                    'status': 'fail',
                    'bim_create_form_errors': bim_create_form_errors[0]
                }

        return HttpResponse(json.dumps(res), content_type='application/json')


# class BIMDetailView(LoginRequiredMixin, View):
#
#     def get(self, request):
#         ret = dict()
#         admin_user_list = []
#         if 'equipment_number' in request.GET and request.GET['equipment_number']:
#             eqeuipment = get_object_or_404(Equipment_info, pk=request.GET['equipment_number'])
#             # work_order_record = eqeuipment.workorderrecord_set.all().order_by('add_time')
#             # try:
#             #     role = Role.objects.get(title="管理")
#             #     admin_user_ids = role.userprofile_set.values('id')
#             #     for admin_user_id in admin_user_ids:
#             #         admin_user_list.append(admin_user_id['id'])
#             # except Exception:
#             #     pass
#             # user_list = [work_order.proposer_id, work_order.approver_id, work_order.receiver_id]
#             # user_list.extend(admin_user_list)
#
#             # 和工单无关联的用户禁止通过手动指定ID的形式非法获取数据
#             # if request.user.id in user_list:
#             #     ret['work_order'] = work_order
#             #     ret['work_order_record'] = work_order_record
#             # else:
#             #     ret['ban'] = 'ban'
#         ret['equipment_info']=eqeuipment
#         return render(request, 'equipment/eim/bim_detail.html', ret)


class BIMDeleteView(LoginRequiredMixin, View):

    def post(self, request):
        ret = dict(result=False)
        Equipment_info.objects.get(equipment_number=request.POST['equipment']).delete()
        ret['result'] = True
        return HttpResponse(json.dumps(ret), content_type='application/json')